package org.lzfto.flink.demo.common;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.ObjectUtils;
import org.lzfto.flink.demo.common.table.PhysicalBasicTable;
import org.lzfto.flink.demo.common.table.PhysicalCustomJdbcTable;
import org.lzfto.flink.demo.common.table.PhysicalStandardTable;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;

public class Configuration {
	private List<PhysicalBasicTable> tables;
	/**
	 * 环境名称。各个配置通常根据此选择对应的配置
	 */
	private String env;
	private List<Dir> fileDirectory;
	
	private static  Configuration conf;
	

	public List<PhysicalBasicTable> getTables() {
		return tables;
	}
	public String getEnv() {
		return env;
	}
	public List<Dir> getFileDirectory() {
		return fileDirectory;
	}
	
	/**
	 * 获取当前环境的文件路径
	 * @return
	 */
	public String getEnvDirectory() {
		if (ObjectUtils.isEmpty(fileDirectory)){
			return "";
		}
		for(Dir item:fileDirectory) {
			if (item.env().equals(this.env)) {
				return item.directory();
			}
		}
		return "";
	}

	public static void init() {
		Configuration config = new Configuration();
		List<PhysicalBasicTable> tables = new ArrayList<>();
		String env=null;
		List<Dir> fileDirectory=null;
		try (InputStream inputStream = PhysicalBasicTable.class.getClassLoader().getResourceAsStream("config.json")) {
			if (inputStream != null) {
				// 将 InputStream 转换为字符串
				String jsonContent = new String(inputStream.readAllBytes());
				// 使用 Fastjson 2 解析 JSON 字符串为 JSONObject
				JSONObject jsonObject = JSON.parseObject(jsonContent);

				// 访问 JSON 对象的字段
				env = jsonObject.getString("env");
				JSONArray fileJa=jsonObject.getJSONArray("fileDirectory");
				if (fileJa!=null) {
					fileDirectory=fileJa.toList(Dir.class);
				}
				
				//构建文件信息
				
				
				//构建表
				JSONArray ja = jsonObject.getJSONArray("tables");

				if (ja != null && ja.size() > 0) {
					int len = ja.size();
					for (int i = 0; i < len; i++) {
						JSONObject item = ja.getJSONObject(i);
						PhysicalBasicTable table = null;
						if (item.getString("idColCode") != null) {
							table = JSON.to(PhysicalCustomJdbcTable.class, item);
							tables.add(table);
						} else {
							table = JSON.to(PhysicalStandardTable.class, item);
							tables.add(table);
						}
						System.out.println("找到表-env=" + table.getEnv() + ",direction=" + table.getDirection() + ",name="
								+ table.getTableName());
					}
				}

			} else {
				System.err.println("config.json not found in resources!");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		config.env=env;
		config.fileDirectory=fileDirectory;
		config.tables=tables;
		conf=config;
	}
	
	public static Configuration getConf() {
		return conf;
	}
	
	record Dir(String env,String directory) {}

}
